package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Aluno;

public class AlunoDaoImpl implements AlunoDao {

	Connection c;

	public AlunoDaoImpl() {
		GenericDao gDao = new GenericDao();
		c = gDao.getConnection();
	}

	@Override
	public void salvaAluno(Aluno aluno) throws SQLException {
		String sql = "INSERT INTO alunos VALUES (?,?,?,?,?,?,?,?,?,?,?)";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, aluno.getNomeAluno());
		ps.setInt(2, aluno.getRE());
		ps.setString(3, aluno.getEndereco());
		ps.setInt(4, aluno.getTelefoneRes());
		ps.setInt(5, aluno.getTelefoneCel());
		ps.setString(6, aluno.getEmail());
		ps.setInt(7, aluno.getCep());
		ps.setString(8, aluno.getBairro());
		ps.setString(9, aluno.getComplemento());
		ps.setInt(10, aluno.getNum());
		ps.setInt(11, aluno.getIdAluno());

		ps.execute();
		ps.close();

	}

	@Override
	public void editaAluno(Aluno aluno) throws SQLException {
		String sql = "UPDATE alunos SET nomeAluno = ?, " + "endereco = ?, "
				+ "telefoneRes = ?, " + "telefoneCel = ?, " + "email = ?, "
				+ "cep = ?, " + "bairro = ?, " + "complemento = ?, "
				+ "RE = ?, " + "num = ? WHERE idAluno = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, aluno.getNomeAluno());
		ps.setInt(2, aluno.getRE());
		ps.setString(3, aluno.getEndereco());
		ps.setInt(4, aluno.getTelefoneRes());
		ps.setInt(5, aluno.getTelefoneCel());
		ps.setString(6, aluno.getEmail());
		ps.setInt(7, aluno.getCep());
		ps.setString(8, aluno.getBairro());
		ps.setString(9, aluno.getComplemento());
		ps.setInt(10, aluno.getNum());
		ps.setInt(11, aluno.getIdAluno());
		ps.execute();
		ps.close();

	}

	@Override
	public void excluiAluno(Aluno aluno) throws SQLException {
		String sql = "DELETE alunos WHERE idAluno = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, aluno.getIdAluno());
		ps.execute();
		ps.close();

	}

	@Override
	public Aluno pesquisaAluno(Aluno aluno) throws SQLException {
		Aluno a = new Aluno();
		String sql = "SELECT RE, nomeAluno, endereco, telefoneRes, telefoneCel, "
				+ "email, cep, bairro, complemento, num FROM alunos "
				+ "WHERE idAluno = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, aluno.getRE());
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			a.setIdAluno(rs.getInt("idAluno"));
			a.setNomeAluno(rs.getString("nomeAluno"));
			a.setEndereco(rs.getString("endereco"));
			a.setTelefoneRes(rs.getInt("telefoneRes"));
			a.setTelefoneCel(rs.getInt("telefoneCel"));
			a.setEmail(rs.getString("email"));
			a.setCep(rs.getInt("cep"));
			a.setBairro(rs.getString("bairro"));
			a.setComplemento(rs.getString("complemento"));
			a.setNum(rs.getInt("num"));
			a.setRE(rs.getInt("RE"));
		}
		ps.close();
		rs.close();
		return a;
	}

}
